import axios        from './api.request';
import qs           from  'qs';
import { typeOf, getFormData, getRequestUrl, getSign, hasFileToFormData } from './util';

const contentTypeList = ["","application/json;charset=utf-8","application/x-www-form-urlencoded;charset=UTF-8","multipart/form-data","text/xml"];

/**
 * @param  {Object}    apiObj 
 * fileData 文件集合 {key: [file]}
 * contentTypeNum: 传输类型
 * timeout: 超时时间
 */
export const $request = (route, requedata, method = 'post' , apiObj = {}) => {
    let requeUrl = getRequestUrl(route);
    let axiosObj = {
        url: requeUrl,
        headers: {},
        method
    };
    const {
        hasSessionId = true,
        fileData,
        isFormData,
        isNoString,
        contentTypeNum,
        timeout,
    } = apiObj;
    
    if(hasSessionId) {
        let signData = {};
        if(typeOf(requedata)==='object') { //只执行字符串签名
            for (let key in requedata) {
                let item = requedata[key]
                let t = typeOf(item)
                if(t==="string" || t==="number") signData[key] = item
                    else console.log('requedata-other',key,item);
            };
        };
        requedata = getSign(route,signData);
    };

    if(method=='post') {
        if(fileData) {
            axiosObj['data'] = hasFileToFormData(requedata,fileData);
            if(apiObj.progress) axiosObj['onUploadProgress'] = apiObj.progress
        }else if(isFormData){
            axiosObj['data'] = getFormData(requedata);
        }else if(isNoString){
            axiosObj['data'] = requedata;
        }else{
            axiosObj['data'] = qs.stringify(requedata);
        };
    }else {
        axiosObj['params'] = requedata;
    };

    if(contentTypeNum) axiosObj["headers"]["Content-Type"] = contentTypeList[contentTypeNum];
    if(timeout) axiosObj["timeout"] = timeout;
    
    return axios.request(axiosObj);
};

export const $post = (route, requedata, apiObj) => {
    return $request(route, requedata, 'post', apiObj);
};

export const $get = (route, requedata = {}, apiObj) => {
    return $request(route, requedata, 'get', apiObj);
};